"use strict";
const fs = require('fs');
const path = require('path');
const codeWriter = require('./generate-code');

const tsutils = new codeWriter();

module.exports = generatePkg;


/**生成UI包路径 ResEnum 和UI绑定 BuildAllUI*/
function generatePkg(cb) {
    const ui_pkg = path.resolve(__dirname, "../UIProject/assets")

    tsutils.reset();
    fs.readdir(ui_pkg, (err, res) => {

        if (err || !res) {
            console.log(err);
            return void cb();
        }

        tsutils.writeln(`/** 自动生成代码 */`);
        tsutils.writeln('export enum ResEnum {');
        tsutils.incIndent();

        for (let dir of res) {
            tsutils.writeln('{0} = "ui/{1}",', dir, dir);
        }

        tsutils.endBlock();
        tsutils.save(path.resolve(__dirname, "../src/module/common/ResEnum.ts"));
        generateUI(cb, res);

    })
}

function generateUI(cb, dir) {
    fs.readFile(path.resolve(__dirname, "../src/module/common/BuildAllUI.ts"), { encoding: "utf-8" }, (err, data) => {

        if (err || !data) {
            console.log(err);
            return void cb();
        }

        let flg = '//====CUSTOM====';

        tsutils.reset();
        let value = data.toString().split(flg)[1] || "";
        tsutils.writeln('/** 自动生成代码 */');

        for (let elm of dir) {
            let fp = path.resolve(__dirname, "../src/moduleui/", elm, elm + "Binder.ts")

            if (!fs.existsSync(fp)) {
                console.log("不存在：", fp);
                continue;
            }

            tsutils.writeln('import {0}Binder from "../../moduleui/{1}/{2}Binder"', elm, elm, elm)
        }


        tsutils.writeln();

        for (let elm of dir) {
            tsutils.writeln('{0}Binder.bindAll();', elm);
        }

        tsutils.writeln(flg);
        tsutils.writeContinue(value);
        tsutils.save(path.resolve(__dirname, "../src/module/common/BuildAllUI.ts"))
        cb();

    })
}
